import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:sptapp/api/interface/home_api.dart';

import '../../api/interface/user_api.dart';
import '../../api/request/response_data.dart';
import '../../basic/base_info.dart';
import '../../config/const.dart';
import '../../moudle/common_info.dart';
import '../../moudle/event_bus.dart';
import '../../moudle/message.dart';
import '../../widget/common_widget.dart';

class MinAddDeviceInput extends StatefulWidget {
  final Map? deviceInfo;
  const MinAddDeviceInput({super.key,this.deviceInfo});

  @override
  State<MinAddDeviceInput> createState() => _MinAddDeviceInputState();
}

class _MinAddDeviceInputState extends State<MinAddDeviceInput> {

  TextEditingController accountController = TextEditingController();
  TextEditingController nameController = TextEditingController();
  TextEditingController phoneController = TextEditingController();
  TextEditingController addressController = TextEditingController();
  String account = '';
  String name = '';
  String phone = '';
  String address = '';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print('sn===== ${widget.deviceInfo}');
    if(widget.deviceInfo != null){
      accountController.text = widget.deviceInfo!['sn'] ?? '';
      account = widget.deviceInfo!['sn'] ?? '';

      phoneController.text = widget.deviceInfo!['phone'] ?? '';
      phone = widget.deviceInfo!['phone'] ?? '';

      addressController.text = widget.deviceInfo!['location'] ?? '';
      address = widget.deviceInfo!['location'] ?? '';

    }
    nameController.text = '3800 Series';
    name = '3800 Series';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: defaultBlackBgColor,
      body: Container(
        padding: EdgeInsets.symmetric(horizontal: 48.w),
        child: Column(
          children: [
            SizedBox(height: ScreenUtil().statusBarHeight + 40.w,),
            myCustomCenterTitleAppBar('Add new device'),
            SizedBox(height: 60.w,),
            Visibility(child: Container(
              width: 654.w,
              height: 108.w,
              padding: EdgeInsets.symmetric(horizontal: 30.w),
              decoration: BoxDecoration(
                  border: Border.all(color: Color.fromRGBO(255, 255, 255, 0.5),width: 1.w),
                  borderRadius: BorderRadius.circular(20.w)
              ),
              child:  Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(child: TextField(
                    //控制器
                    textInputAction: TextInputAction.done,
                    controller: accountController,
                    maxLength: 14,
                    maxLines: 1,
                    //是否自动更正
                    autocorrect: true,
                    //是否自动对焦
                    autofocus: false,
                    style: inputStyle,
                    inputFormatters: [
                      FilteringTextInputFormatter.allow(RegExp("[0-9]"))
                    ],
                    decoration: InputDecoration(
                      contentPadding: const EdgeInsets.symmetric(vertical: 0,horizontal: 0),
                      hintText: add_device_hintText.tr,
                      hintStyle: inputHitStyle,
                      counterText: "",
                      border: OutlineInputBorder(
                          borderSide: BorderSide.none),
                    ),
                    onChanged: (val){
                      setState(() {
                        account = val.trim();
                      });
                    },
                  )),
                  SizedBox(width: 20.w,),
                  Visibility(visible: account!=null&&account!.isNotEmpty,
                    child: GestureDetector(
                      onTap: (){
                        setState(() {
                          accountController.text = '';
                          account = '';
                        });
                      },
                      child: Container(
                        child: inputImg,
                      ),
                    ),
                  )
                ],
              ),
            ),visible: widget.deviceInfo == null || widget.deviceInfo!['id'] == null,),
            Visibility(visible: widget.deviceInfo != null && widget.deviceInfo!['id'] != null,child: Container(
              width: 654.w,
              padding: EdgeInsets.symmetric(horizontal: 0.w),
              child:  Text(
                 widget.deviceInfo?['sn'] ?? '' ,
                style: inputStyle,
              ),
            ),),
            SizedBox(height: 32.w,),

            Container(
              width: 654.w,
              height: 108.w,
              padding: EdgeInsets.symmetric(horizontal: 30.w),
              decoration: BoxDecoration(
                  border: Border.all(color: Color.fromRGBO(255, 255, 255, 0.5),width: 1.w),
                  borderRadius: BorderRadius.circular(20.w)
              ),
              child:  Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(child: TextField(
                    //控制器
                    textInputAction: TextInputAction.done,
                    controller: nameController,
                    maxLines: 1,
                    //是否自动更正
                    autocorrect: true,
                    //是否自动对焦
                    autofocus: false,
                    style: inputStyle,
                    inputFormatters: [
                    ],
                    decoration: InputDecoration(
                      contentPadding: const EdgeInsets.symmetric(vertical: 0,horizontal: 0),
                      hintText: 'Edit Name'.tr,
                      hintStyle: inputHitStyle,
                      counterText: "",
                      border: OutlineInputBorder(
                          borderSide: BorderSide.none),
                    ),
                    onChanged: (val){
                      setState(() {
                        name = val.trim();
                      });
                    },
                  )),
                  SizedBox(width: 20.w,),
                  Visibility(visible: name!=null&&name!.isNotEmpty,
                    child: GestureDetector(
                      onTap: (){
                        setState(() {
                          nameController.text = '';
                          name = '';
                        });
                      },
                      child: Container(
                        child: inputImg,
                      ),
                    ),
                  )
                ],
              ),
            ),
            SizedBox(height: 32.w,),

            Container(
              width: 654.w,
              height: 108.w,
              padding: EdgeInsets.symmetric(horizontal: 30.w),
              decoration: BoxDecoration(
                  border: Border.all(color: Color.fromRGBO(255, 255, 255, 0.5),width: 1.w),
                  borderRadius: BorderRadius.circular(20.w)
              ),
              child:  Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(child: TextField(
                    //控制器
                    textInputAction: TextInputAction.done,
                    controller: phoneController,
                    maxLines: 1,
                    //是否自动更正
                    autocorrect: true,
                    //是否自动对焦
                    autofocus: false,
                    style: inputStyle,
                    inputFormatters: [
                    ],
                    decoration: InputDecoration(
                      contentPadding: const EdgeInsets.symmetric(vertical: 0,horizontal: 0),
                      hintText: 'Phone Editor'.tr,
                      hintStyle: inputHitStyle,
                      counterText: "",
                      border: OutlineInputBorder(
                          borderSide: BorderSide.none),
                    ),
                    onChanged: (val){
                      setState(() {
                        phone = val.trim();
                      });
                    },
                  )),
                  SizedBox(width: 20.w,),
                  Visibility(visible: phone!=null&&phone!.isNotEmpty,
                    child: GestureDetector(
                      onTap: (){
                        setState(() {
                          phoneController.text = '';
                          phone = '';
                        });
                      },
                      child: Container(
                        child: inputImg,
                      ),
                    ),
                  )
                ],
              ),
            ),
            SizedBox(height: 32.w,),

            Container(
              width: 654.w,
              height: 108.w,
              padding: EdgeInsets.symmetric(horizontal: 30.w),
              decoration: BoxDecoration(
                  border: Border.all(color: Color.fromRGBO(255, 255, 255, 0.5),width: 1.w),
                  borderRadius: BorderRadius.circular(20.w)
              ),
              child:  Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(child: TextField(
                    //控制器
                    textInputAction: TextInputAction.done,
                    controller: addressController,
                    maxLines: 1,
                    //是否自动更正
                    autocorrect: true,
                    //是否自动对焦
                    autofocus: false,
                    style: inputStyle,
                    inputFormatters: [
                    ],
                    decoration: InputDecoration(
                      contentPadding: const EdgeInsets.symmetric(vertical: 0,horizontal: 0),
                      hintText: 'Edit Address'.tr,
                      hintStyle: inputHitStyle,
                      counterText: "",
                      border: OutlineInputBorder(
                          borderSide: BorderSide.none),
                    ),
                    onChanged: (val){
                      setState(() {
                        address = val.trim();
                      });
                    },
                  )),
                  SizedBox(width: 20.w,),
                  Visibility(visible: address!=null&&address!.isNotEmpty,
                    child: GestureDetector(
                      onTap: (){
                        setState(() {
                          addressController.text = '';
                          address = '';
                        });
                      },
                      child: Container(
                        child: inputImg,
                      ),
                    ),
                  )
                ],
              ),
            ),
            SizedBox(height: 64.w,),
            GestureDetector(
              onTap: (){
                if(account != null && account!.isNotEmpty){
                  _addDevice();
                }
              },
              child: Container(
                decoration: BoxDecoration(
                    color: account != null && account!.isNotEmpty ? themeColor : themeDisableColor,
                    borderRadius: BorderRadius.circular(8.w)
                ),
                height: 108.w,
                alignment: Alignment.center,
                child: Text('Save'.tr,style: TextStyle(
                    color: Colors.white,
                    fontSize: 28.sp
                ),),
              ),
            ),
          ],
        ),
      ),
    );
  }

  _addDevice()async{
    Map<String,dynamic> data = {
      'sn': account,
      'name':name == null || name.isEmpty ? account : name,
      'phone':phone,
      'location':address,
    };
    showLoading();
    ResponseData res;
    if(widget.deviceInfo == null || widget.deviceInfo!['id'] == null){
      res = await UserAPI.addDevice(data);
    }else{
      res = await HomeAPI.deviceSetName(data);
    }
    hideLoading();
    if(res.code == 200){
      LocalBaseInfo.setDeviceNum(account);
      getDevicesList((){
        eventBus.fire(DeviceInfoChange());
        if(widget.deviceInfo != null && widget.deviceInfo!['id'] != null){
          Navigator.of(context).pop();
        }else{
          Navigator.of(context).popUntil(ModalRoute.withName("index"));
        }
        if(baseDevice?['status'].toString() == '2'){
          Navigator.of(context).pushNamed('DeviceNetPage');
        }
      });
    }
  }
}
